
local u = {}

-- Lua implementation of C#'s String.Format method. Tokens are 1-based.
-- 
-- Usage: 
--     string.formatcs("first = {1}, second = {2}, third = {3}", "value one", "value two", "value three")
-- 
-- This example would return the following string:
--     first = value one, second = value two, three = value three
-- 
function u.Format(str, ...) 
	local args = {...};
	local c = #args;
	
	for k=1, c do
		local v = args[k]; 
		str = string.gsub(str, "{"..(k).."}", tostring(args[k]));		
	end
	return str;
end

--- 分割一个字符串
--- 和默认的string.split的区别是支持对分割后的条目进行map
function u.Split(str, sep, mapper)
	local sep, fields = sep or ":", {}
	local pattern = string.format("([^%s]+)", sep)
	str:gsub(pattern
		, 
		function (c) 
			if mapper then
				fields[#fields + 1] = mapper(c);
			else				
				fields[#fields + 1] = c;
			end
		end)
	return fields;
end

-- 计算 UTF8 字符串的长度，每一个中文算一个字符
function u.StrCharLength(input)
	local len  = string.len(input)
	local left = len
	local cnt  = 0
	local arr  = {0, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc}
	while left ~= 0 do
		local tmp = string.byte(input, -left)
		local i   = #arr
		while arr[i] do
			if tmp >= arr[i] then
				left = left - i
				break
			end
			i = i - 1
		end
		cnt = cnt + 1
	end
	return cnt
end

return u
